package com.xkcoding.elasticsearch.config;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: dengkaibing
 * @Description:
 * @Date: 2022/2/21 17:23
 * @company 翼支付
 */
@Configuration
public class EsConfig {
    @Value("${es.nodes.host}")
    private  String esNodes;

    @Value("${es.nodes.account}")
    private  String esAccount;

    @Value("${es.nodes.password}")
    private  String esPassword;

    /**
     * RestHighLevelClient builder, 具体地址配置、账号配置请见申请工单的邮件回复
     *
     * @return RestHighLevelClient
     */
    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient restClintInit() {
        try {
            String[] nodes = esNodes.split(",");
            List<HttpHost> hostList = new ArrayList<>();
            for (String node : nodes) {
                String[] split = node.split(":");
                HttpHost httpHost = new HttpHost(split[0], Integer.parseInt(split[1]), "http");
                hostList.add(httpHost);
            }
            HttpHost[] httpHosts = hostList.toArray(new HttpHost[hostList.size()]);
            RestClientBuilder builder = RestClient.builder(httpHosts);

            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(esAccount, esPassword));
            builder.setHttpClientConfigCallback(httpClientBuilder ->
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                    .setMaxConnPerRoute(10)
                    .setMaxConnTotal(30));
            builder.setRequestConfigCallback(requestConfigBuilder ->
                requestConfigBuilder.setConnectTimeout(3000)
                    .setConnectionRequestTimeout(3000)
                    .setSocketTimeout(5000));
            // RestHighLevelClient实例通过REST low-level client builder进行构造
            return new RestHighLevelClient(builder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
